<template>
  <div class="user">
    <!-- 头部 -->
    <div class="search">
      <a-form ref="formRef" style="padding-top: 20px" :model="form" :hideRequiredMark="true" :label-col="labelCol">
        <a-row :gutter="10">
          <a-col :span="5" :lg="5" :md="7" :xs="7">
            <a-form-item name="nick" label="用户名">
              <a-input v-model:value="form.nickName" placeholder="请输入用户名"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5" :lg="5" :md="7" :xs="8">
            <a-form-item name="userId" label="用户ID">
              <a-input v-model:value="form.userId" placeholder="请输入用户ID"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5" :lg="5" :md="7" :xs="8">
            <a-form-item label="手机号">
              <a-input v-model:value="form.mobile" placeholder="请输入用户手机号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="2" :xs="4" :lg="2" :offset="1">
            <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
          </a-col>
          <a-col :span="3" :offset="1">
            <a-button type="primary" @click="openDrawer" class="d-a-center">高级筛选</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-row justify="end" style="padding: 20px 0px" :gutter="20" v-has="{ a: $route, b: 2 }">
      <!-- <a-col :span="2">
        <a-button type="info" @click="importData">导入客户</a-button>
      </a-col> -->
      <!-- <a-col :span="2" :offset="1">
        <a-button type="primary" @click="userSendMsg">自定义发送短信</a-button>
      </a-col> -->
      <a-col :span="2" :offset="1" :xs="7" :lg="2">
        <a-button type="info" @click="exportData" class="d-a-center">导出客户数据</a-button>
      </a-col>
      <a-col :span="2" :offset="1" :xs="7" :lg="2">
        <a-button type="primary" @click="send" :loading="msgLoading" class="d-a-center">发送短信</a-button>
      </a-col>
      <a-col :span="2" :offset="1" :xs="7" :lg="2">
        <a-button type="info" @click="systemNotice" :loading="sysLoading" class="d-a-center">系统通知</a-button>
      </a-col>
    </a-row>
    <!-- 列表 -->
    <a-table
      rowKey="userId"
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="{ selectedRowKeys: rowSelection.selectedRowKeys, ...rowSelection }"
      :scroll="{ y: 540 }"
    >
      <template #status="{ record }">
        <a-tag :color="record.status == 1 ? 'success' : ''">{{ record.status == 1 ? '已实名' : '未实名' }}</a-tag>

        <!-- <a-switch
          v-model:checked="record.isDele"
          :checkedValue="1"
          :unCheckedValue="0"
          @change="changeStatus(record.status, index)"
        /> -->
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record.userId, listPage, form, advancedForm, 0)" v-has="{ a: $route, b: 2 }" class="d-a-center"
          >查看</a-button
        >
        <a-button type="link" @click="look(record.userId, listPage, form, advancedForm, 1)" v-has="{ a: $route, b: 2 }" class="d-a-center"
          >编辑</a-button
        >
        <!-- <a-button type="link" @click="deal(record.key)">编辑</a-button> -->
      </template>
    </a-table>
    <a-divider></a-divider>
    <!-- <a-row>
      <a-col :span="3" :offset="1">
        <a-button type="primary" @click="enableUser">启用</a-button>
      </a-col>
      <a-col :span="2">
        <a-button type="danger" @click="disableUser">停用</a-button>
      </a-col>
    </a-row> -->

    <!-- 高级筛选抽屉 -->
    <a-drawer width="40%" :destroyOnClose="true" v-model:visible="visible" class="custom-class" title="高级筛选" placement="right">
      <a-form :label-col="labelCol" :model="advancedForm">
        <!-- <a-form-item label="地理位置">
          <a-input
            v-model="advancedForm.address"
            placeholder="请输入地理位置"
          ></a-input>
        </a-form-item> -->
        <a-form-item label="认证状态">
          <a-select
            ref="select"
            v-model:value="advancedForm.attestStatus"
            style="width: 120px"
            @focus="focus"
            @change="handleChange"
            placeholder="请选择实名认证状态"
          >
            <a-select-option v-for="item in isRealNameList" :value="item.id" :key="item.id">{{ item.title }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="注册时间">
          <a-range-picker v-model:value="value1" @change="selectTime" />
        </a-form-item>
        <a-form-item label="注册渠道">
          <!-- <a-input
            v-model="advancedForm.registSource"
            placeholder="请输入注册渠道"
          ></a-input> -->
          <a-select ref="select" v-model:value="advancedForm.channel" style="width: 120px" @focus="focus" placeholder="请选择注册渠道">
            <a-select-option v-for="item in registSourceList" :value="item.title" :key="item.id">{{ item.title }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="消费金额">
          <a-slider
            v-model:value="sliderValue"
            @change="changeConsumePrice"
            range
            :tooltipVisible="true"
            :marks="marks"
            :min="0"
            :max="9999"
          />
        </a-form-item>
        <a-form-item label="订单数量">
          <a-slider
            v-model:value="sliderValue1"
            @change="changeOrderNumber"
            range
            :tooltipVisible="true"
            :marks="marks1"
            :min="0"
            :max="999"
          />
        </a-form-item>
        <!-- <a-form-item label="状态">
          <a-select
            ref="select"
            v-model:value="advancedForm.isDele"
            style="width: 120px"
            @focus="focus"
            @change="handleChange"
            placeholder="请选择当前用户状态"
          >
            <a-select-option
              v-for="item in statusList"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item> -->
      </a-form>
      <a-row style="margin-top: 50px">
        <a-col :span="4" :offset="10">
          <a-button type="primary" size="large" @click="advancedSearch" class="d-a-center">搜索</a-button>
        </a-col>
      </a-row>
    </a-drawer>

    <!-- 自定义发送短信：天天奇葩的要求 -->
    <a-modal :visible="sendMsgVisible" title="发送短信" @ok="confirmSendMsg">
      <a-form :model="userSendMsgForm" :rules="rules" ref="userSendMsgFormRef">
        <a-form-item label="手机号" name="mobile" has-feedback>
          <a-row style="align-items: center" :gutter="20">
            <a-col :span="20">
              <a-input placeholder="请输入手机号" v-model:value="userSendMsgForm.mobile"></a-input>
            </a-col>
            <a-col :span="4">
              <plus-outlined />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="短信内容" name="content">
          <a-textarea placeholder="请输入内容" v-model:value="userSendMsgForm.content"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 发送短信 -->
    <template v-if="msgVisible">
      <SendMsg
        :visible="msgVisible"
        :modalType="modalType"
        @closeModal="closeMsg"
        :longs="myFinalLong"
        :list="mobileList"
        :userDto="{ ...advancedForm, ...form }"
        :userType="myFinalType"
      >
      </SendMsg>
    </template>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, onMounted, createVNode, toRefs } from 'vue'
import { CheckOutlined, EditOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal, message, notification } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import SendMsg from '@/views/user/components/SendMsg'
import { selectAllUser, getUserExcel, selectAllUserExport, selectAllUserIds } from '@/api/user/index'
import { useModal, useSelects } from '@/hooks'
import { deleteObjBlank } from '@/assets/js/common.js'
import { validatorPhone } from '@/assets/js/validate'
export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
    const formRef = ref('')
    const form = reactive({})
    const data = reactive({
      loading: false,
      list: [],
      advance: false, //是否是高级搜索
      mobileList: [],
      value1: '',
      sendMsgVisible: false, //自定义发送短信弹窗
      userSendMsgForm: {},
      userSendMsgFormRef: '',
      msgLoading: false,
      sysLoading: false,
      listPage: 1,
      toListPage: 1,
      toAdvancedForm: '',
      toForm: ''
    })
    const msgVisible = ref(false)
    const modalType = ref(0)

    const advancedForm = reactive({})

    const selectList = ref([]) //选中的列表

    const rules = reactive({
      content: [
        {
          required: true,
          message: '请输入发送内容!',
          trigger: 'blur'
        }
      ],
      mobile: [
        {
          required: true,
          validator: validatorPhone,
          trigger: 'blur'
        }
      ]
    })
    const isRealNameList = reactive([
      {
        title: '已实名',
        id: 1
      },
      {
        title: '未实名',
        id: 0
      }
    ])
    const statusList = reactive([
      {
        title: '启用',
        id: 0
      },
      {
        title: '停用',
        id: 1
      }
    ])
    const sliderValue = ref([0, 9999])
    const sliderValue1 = ref([0, 999])
    const marks = ref({
      0: '0',
      9999: {
        style: {
          color: '#f50'
        },
        label: '9999'
      }
    })
    const marks1 = ref({
      0: '0',
      999: {
        style: {
          color: '#f50'
        },
        label: '999'
      }
    })

    const loading = ref(false) //表格的加载
    const visible = ref(false)
    const myFinalLong = computed(() => {
      return data.mobileList.length
    })

    const myFinalType = computed(() => {
      return '2'
    })
    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 30,
      total: 0,
      pages: 0 //所有页码
    })

    const changeConsumePrice = e => {
      console.log(e, '范围')
      advancedForm.startPrice = e[0]
      advancedForm.endPrice = e[1]
    }
    const changeOrderNumber = e => {
      advancedForm.startNumber = e[0]
      advancedForm.endNumber = e[1]
    }
    // 查询
    const search = () => {
      console.log(form, '表单内容')
      if (Object.keys(form).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      deleteObjBlank(form)
      page.current = 1
      data.toListPage = 1
      data.toForm = ''
      data.toAdvancedForm = ''
      rowSelection.selectedRowKeys = []
      init()
      // formRef.value
      //   .validate()
      //   .then(() => {
      //     console.log("values", formState, toRaw(formState));
      //   })
      //   .catch((error) => {
      //     console.log("error", error);
      //   });
    }
    const confirmSendMsg = () => {
      data.userSendMsgFormRef.validate().then(async () => {})
    }
    // 选择时间
    const panelChange = (date, dateString) => {
      advancedForm.startTime = dateString[0]
      advancedForm.endTime = dateString[1]
    }
    const registSourceList = reactive([
      {
        title: '微信',
        id: 0
      },
      {
        title: '旧版',
        id: 1
      },
      {
        title: '点点医生',
        id: 2
      },
      {
        title: '市民卡',
        id: 3
      },
      {
        title: '惠医科技',
        id: 4
      }
    ])
    const columns = [
      {
        title: '用户ID',
        dataIndex: 'userId',
        className: 'table',
        align: 'center'
      },
      {
        title: '用户名',
        dataIndex: 'nick',
        className: 'table',
        align: 'center',
        sort: true
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        className: 'table',
        align: 'center'
      },
      // {
      //   title: "地理位置",
      //   dataIndex: "address",
      //   className: "table",
      //   align: "center",
      // },
      {
        title: '注册日期',
        dataIndex: 'createdAt',
        className: 'table',
        align: 'center',
        sorter: true
      },
      {
        title: '消费金额',
        dataIndex: 'orderPriceSum',
        className: 'table',
        align: 'center',
        sorter: (a, b) => {
          return a.orderPriceSum - b.orderPriceSum
        }
      },
      {
        title: '注册渠道',
        dataIndex: 'registSource',
        className: 'table',
        align: 'center'
      },
      {
        title: '订单数量',
        dataIndex: 'orderNum',
        className: 'table',
        align: 'center',
        sorter: (a, b) => {
          return a.orderNum - b.orderNum
        }
      },
      {
        title: '实名制状态',
        dataIndex: 'status',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'status'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['30', '50', '70'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      data.listPage = page.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      if (data.advance) {
        // 如果是高级查询
        init(advancedForm)
      } else {
        init()
      }
    }
    // useSelects
    const { renderData, rowSelection } = useSelects({
      key: 'userId'
    })

    const userSendMsg = () => {
      data.sendMsgVisible = true
    }
    const changeStatus = (e, index) => {
      console.log(e.index, '是否禁用')
      // 弹框提示？确定上下架吗
      const { closeModal } = useModal.confirm({
        title: () => '确定停用当前用户吗?',
        icon: () => createVNode(ExclamationCircleOutlined),

        class: 'test'
      })
    }
    const openDrawer = () => {
      visible.value = true
    }
    const selectTime = (e, str) => {
      console.log(e, str, '选择时间')
      advancedForm.createdAtBegin = str[0]
      advancedForm.createdAtEnd = str[1]
    }
    // 高级筛选
    const advancedSearch = () => {
      if (Object.keys(advancedForm).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      console.log(advancedForm)
      page.current = 1
      data.toListPage = 1
      ;(data.pageNum = 1), (data.toForm = '')
      data.toAdvancedForm = ''
      rowSelection.selectedRowKeys = []
      init(advancedForm)
      visible.value = false
      data.advance = true
      // close();
    }
    // /启用
    const enableUser = () => {
      const { closeModal } = useModal.confirm({
        title: '确定启用所选用户吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        cancelText: '取消'
      })
    }
    // 停用
    const disableUser = () => {
      const { closeModal } = useModal.confirm({
        title: '确定停用所选用户吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消'
      })
    }
    // 导出客户数据
    const exportData = async () => {
      if (rowSelection.selectedRowKeys.length == 0) {
        message.warning('请选择要导出的用户')
        return
      }

      const { closeModal } = useModal.confirm({
        // ${rowSelection.selectedRowKeys.length}条
        title: `确认导出当前${rowSelection.selectedRowKeys.length}条数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
          let obj = {
            ...form,
            ...advancedForm,
            userIds: rowSelection.selectedRowKeys
          }

          selectAllUserExport({
            ...obj
          }).then(res => {
            console.log(res)
            // console.log(url);
            let link = document.createElement('a')
            //创建一个a标签
            link.style.display = 'none'
            //将a标签隐藏
            link.href = res.object
            //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
            link.setAttribute('download', '护士')
            // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
            document.body.appendChild(link)
            //将上面创建的a标签加入到body的尾部
            link.click()
            //执行a标签
            closeModal()
          })
          return
        },

        class: 'test'
      })
    }
    // 发送短信
    const send = async () => {
      if (rowSelection.selectedRowKeys.length == 0) {
        message.warning('请选择你要发送的用户')
        return
      }

      data.mobileList = rowSelection.selectedRowKeys

      msgVisible.value = true
    }
    // 系统通知
    const systemNotice = async () => {
      if (rowSelection.selectedRowKeys.length == 0) {
        message.warning('请选择你要发送的用户')
        return
      }

      data.mobileList = rowSelection.selectedRowKeys
      modalType.value = 1
      msgVisible.value = true
    }

    const closeMsg = () => {
      console.log('关闭信息')
      msgVisible.value = false
    }

    // 查看
    const look = (key, listPage, form, advancedForm, isLook) => {
      console.log('查看9999999999999', form, listPage, advancedForm)
      if (data.toForm != '') {
        handleForm(data.toForm)
      }
      if (data.toAdvancedForm != '') {
        advancedForm = data.advancedForm
      }
      form = JSON.stringify(form)
      advancedForm = JSON.stringify(advancedForm)
      router.push({
        path: '/user/client/client-detail',
        query: {
          id: key,
          form: form,
          advancedForm: advancedForm,
          listPage: listPage,
          isLook: isLook
        }
      })
    }

    // 处理
    const deal = (key, isEdit) => {
      router.push({
        path: '/user/client/client-detail',
        query: {
          isEdit: 1
        }
      })
    }

    function findStr(str, cha, num) {
      let x = str.indexOf(cha)
      for (let i = 0; i < num; i++) {
        x = str.indexOf(cha, x + 1)
      }
      return x
    }

    function handleForm(str) {
      let a = JSON.parse(str)
      if (typeof a.mobile != undefined) {
        form.mobile = a.mobile
      }
      if (typeof a.userId != undefined) {
        form.userId = a.userId
      }
      if (typeof a.nickName != undefined) {
        form.nickName = a.nickName
      }
    }
    let detailUrl = decodeURI(router.options.history.state.forward)
    if (detailUrl != null) {
      let sta = detailUrl.indexOf('client-detail') != -1
      console.log('sta', detailUrl)
      if (sta) {
        let detailUrlLength = detailUrl.length
        let detailUrlLocation = detailUrl.lastIndexOf('=')
        let endData = detailUrl.substr(detailUrlLocation + 1, detailUrlLength - detailUrlLocation)
        data.toListPage = endData
        data.listPage = endData
        console.log('listPage', data.listPage)
        let formLocationStart = findStr(detailUrl, '=', 1) + 1
        let formLocation = findStr(detailUrl, '&', 1)
        data.toForm = detailUrl.substring(formLocation, formLocationStart)
        console.log('toForm', data.toForm)
        let advanceLocation = detailUrl.lastIndexOf('&')
        let advanceLocationStart = detailUrl.lastIndexOf('=', detailUrl.lastIndexOf('=') - 1) + 1
        data.toAdvancedForm = detailUrl.substring(advanceLocationStart, advanceLocation)
        console.log('toAdvancedForm', data.toAdvancedForm)
        data.advancedForm = JSON.parse(data.toAdvancedForm)
        handleForm(data.toForm)
        console.log('高级搜索', data.advancedForm, '普通搜索', form)
      }
      init()
    }
    async function init(search) {
      console.log('search', search)
      console.log(111, data.toAdvancedForm, 222, data.toForm)
      console.log(222, data.advancedForm, 333, data.form)
      if (typeof search == 'undefined') {
        if (data.toAdvancedForm != '{}') {
          console.log('高级')
          search = data.advancedForm
        } else if (data.toForm != '{}') {
          console.log('普通')
          handleForm(data.toForm)
        }
      }
      data.loading = true
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...form,
        ...search
      }
      console.log('obj777777777777', obj)
      let res = await selectAllUser(obj)
      if (res.success) {
        res.object.pagedData.list.map(el => {
          el.key = el.id
          if (!el.orderPriceSum) {
            el.orderPriceSum = 0
          }
          if (!el.orderNum) {
            el.orderNum = 0
          }
        })
        data.list = res.object.pagedData.list
        page.total = res.object.pagedData.total
        // renderData.value = res.object.allUserIds;
        getSelectAllUserIds(obj)
      }
      data.loading = false
    }
    const getSelectAllUserIds = obj => {
      selectAllUserIds(obj).then(res => {
        renderData.value = res.object
      })
    }
    onMounted(() => {
      console.log('onMountedonMountedonMounted', data.toListPage, data.toForm, data.toAdvancedForm)
      if (data.toListPage != 1 || data.toForm != '{}' || data.toAdvancedForm != '{}' || data.toForm == '' || data.toAdvancedForm == '') {
        page.current = data.toListPage
        console.log(22222222222)
        if (data.toAdvancedForm != '{}' && data.toForm == '{}') {
          console.log('高级筛选00000000000000')
          console.log(data.advancedForm)
          init(data.advancedForm)
        } else if (data.toForm != '{}' && data.toAdvancedForm == '{}') {
          console.log('普通搜索11111111111111')
          init()
        }
      } else if (
        data.toListPage == 1 &&
        (data.toForm == '{}' || data.toForm == '') &&
        (data.toAdvancedForm == '{}' || data.toAdvancedForm == '')
      ) {
        page.current = data.listPage
        console.log(1111111111111111)
        init()
      }
    })
    return {
      ...toRefs(data),
      formRef,
      handleForm,
      findStr,
      form,
      columns,
      loading,
      pagination,
      handleTableChange,
      search,
      panelChange,
      deal,
      look,
      rowSelection,
      changeStatus,
      myFinalType,
      myFinalLong,
      labelCol: {
        style: {
          fontWeight: 'bolder',
          width: '100px'
        }
      },
      exportData,
      send,
      systemNotice,
      enableUser,
      disableUser,
      visible,
      openDrawer,
      advancedForm,
      isRealNameList,
      statusList,
      advancedSearch,
      sliderValue,
      sliderValue1,
      marks,
      marks1,
      changeOrderNumber,
      msgVisible,
      closeMsg,
      modalType,
      registSourceList,
      selectTime,
      changeConsumePrice,
      userSendMsg,
      rules,
      confirmSendMsg
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    SendMsg,
    PlusOutlined
  }
}
</script>

<style scoped lang="less">
.img {
  width: 50px;
  height: 50px;
}

.title {
  font-weight: bold;
}

.search {
  background-color: #e6e6e6;
  margin-bottom: 20px;
}
</style>
